package com.sprint.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sprint.entities.CommonResult;
import com.sprint.entities.Payment;
import com.sprint.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class CircleBreakerController {
    @Autowired
    private RestTemplate restTemplate;


    @Value("${server.port}")
    private String serverport;

    @Value("${service-url.nacos-user-service}")
    private String serviceURL;

    @GetMapping(value = "/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback" ) //未配置兜底函数，报错error page
    //@SentinelResource(value = "fallback",fallback = "handlerFallback") //配置兜底函数， 不会error page，返回错误commonResult
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //配置熔断函数，只有达到熔断阈值才起作用，否则报error page
     @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler"
                ,exceptionsToIgnore = {IllegalArgumentException.class} //IllegalArgumentException排除不考虑，不走兜底handlerfallback
     )
    //同时启动fallback和blockhandler，如果限流或者降级就进入blockhandler

    public CommonResult<Payment> paymentSQL(@PathVariable Long id){

        String path = serviceURL + "/paymentSQL/" + id;
        System.out.println("request path:" + path );
         CommonResult<Payment> result = restTemplate.getForObject(serviceURL + "/paymentSQL/" + id, CommonResult.class);
         if(id == 4 ){
            throw new IllegalArgumentException("IllegalArgumentException, 非法参数异常");
        }
        else if(result.getData() ==null ){
            throw new NullPointerException("Null Point Exception, 该ID没有对应记录，控制住异常");
        }
        return result;
    }

    //兜底行数
    public CommonResult<Payment> handlerFallback(@PathVariable Long id, Throwable throwable){
        Payment payment = new Payment(id,null);
        return new CommonResult<>(444,"兜底函数handlerFallback ，exception内容"+ throwable.getMessage(),payment);
    }

    //兜底行数
    public CommonResult<Payment> blockHandler(@PathVariable Long id, BlockException e){
        Payment payment = new Payment(id,null);
        return new CommonResult<>(445,"兜底函数blockHandler ，exception内容"+ e.getMessage(),payment);
    }

    @Autowired
    //OPEN feign方式
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL2(@PathVariable Long id){
        CommonResult<Payment> result = paymentService.paymentSQL(id);
        return result;
    }
}
